package cn.ccccltd.waf.message.base.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import cn.ccccltd.waf.message.config.MessageRegisterCenter;
import cn.ccccltd.waf.message.constant.MessageConstants;
import cn.ccccltd.waf.message.model.MessageCommon;
import cn.ccccltd.waf.message.model.params.QueryItem;
import cn.ccccltd.waf.message.model.result.Data;
import cn.ccccltd.waf.message.model.result.MessageResult;
import cn.ccccltd.waf.message.model.vo.Authority;
import cn.ccccltd.waf.message.model.vo.GeneralMessage;
import cn.ccccltd.waf.message.model.vo.Log;
import cn.ccccltd.waf.message.model.vo.MessageSms;
import cn.ccccltd.waf.message.thread.threadlocal.MessageContext;
import cn.ccccltd.waf.message.util.MessageUtils;
import cn.ccccltd.waf.message.util.NameUtil;
import cn.ccccltd.waf.message.util.sql.SqlTools;

/**
 * 创建日期:2017年11月21日
 * Title: 公共查询接口，与消息类型没有关系的
 * Description：对本文件的详细描述，原则上不能少于50字
 * @author yangjingjiang
 * @mender：（文件的修改者，文件创建者之外的人）
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Component("seachData")
public class SeachData {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 功能: 查询模块项字典<br>
	 * 作者: yangjingjiang <br>
	 * 创建日期:2017年11月20日 <br>
	 * 修改者: mender <br>
	 * 修改日期: modifydate <br>
	 * @param params
	 * @return
	 */
	@SuppressWarnings({ "unchecked" })
	public Object queryModuleItem(Map<String,String> params) {
		
		Assert.hasText(params.get("sendSystemid"), "系统id不能为空!");
		
		//查询条件
		List<QueryItem> list = (List<QueryItem>) MessageContext.getValue(MessageConstants.QUERYITEMS);
		
		Assert.notEmpty(list,"缺少系统id查询项条件!");
		
		String value = list.get(0).getValue();
		
		//不进行数据过滤及分页
		MessageContext.setValue(MessageConstants.NOTFILTERDATA, MessageConstants.TRUE);
		
		String selectSql = "SELECT DISTINCT business_module nodeid, business_module nodetitle , 'leaf' nodetype ,'2' grade ,send_systemid pnodeid FROM  waf_msg_message_common WHERE send_systemid =?";
		
		
		List<Map<String,Object>> queryList = jdbcTemplate.queryForList(selectSql, new Object[] {value});
		
		MessageResult rs = new MessageResult("true", "200", "加载数据成功！", queryList);
		
		return rs;
	}
	
	/**
	 * 功能: 查询系统模块字典项<br>
	 * 作者: yangjingjiang <br>
	 * 创建日期:2017年11月20日 <br>
	 * 修改者: mender <br>
	 * 修改日期: modifydate <br>
	 * @param params
	 * @return
	 */
	public Object querySystemidItem(Map<String,String> params) {
		
		Assert.hasText(params.get("sendSystemid"), "系统id不能为空!");
		
		//不进行数据过滤及分页
		MessageContext.setValue(MessageConstants.NOTFILTERDATA, MessageConstants.TRUE);
		
		String selectSql = "SELECT DISTINCT send_systemid nodeid,  system_name nodetitle, 'branch' nodetype , '1' grade ,'0' pnodeid FROM  waf_msg_authority ";
		
		// 是否是管理员
		Authority wafMsgAuthority = (Authority) MessageContext.getValue(MessageConstants.SESSION);
		
		List<Map<String,Object>> queryList = new ArrayList<>();
		if (!MessageUtils.isAdmin(wafMsgAuthority)) {
			
			selectSql = selectSql + "WHERE send_systemid =?";
			queryList = jdbcTemplate.queryForList(selectSql, new Object[] {params.get("sendSystemid")});
			
		} else {

			queryList = jdbcTemplate.queryForList(selectSql);
			
		}
		
		MessageResult rs = new MessageResult("true", "200", "加载数据成功！", queryList);
		
		return rs;
		
	}
	
	/**
	 * 功能: 查询日志<br>
	 * 作者: yangjingjiang <br>
	 * 创建日期:2017年11月21日 <br>
	 * 修改者: mender <br>
	 * 修改日期: modifydate <br>
	 * @param params
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Object queryLog(Map<String,String> params) {
		
		Class entityClass = Log.class;
		
		String tableName = NameUtil.getTableName(entityClass.getSimpleName());
		
		String selectSql = SqlTools.getSelectAllProperty(tableName, entityClass);
		
		List queryForList = jdbcTemplate.query(selectSql, new BeanPropertyRowMapper(entityClass));
		
		Data dt = new Data<>();
		String sqlCount = SqlTools.getCountSql(tableName);
		dt.setTotal((Long)queryCountMessage(sqlCount));
		dt.setRows(queryForList);
		
		MessageResult rs = new MessageResult("true", "200", "加载数据成功！", dt);
		
		return rs;
	
	}
	
	/**
	 * 功能: 数量查询<br>
	 * 作者: yangjingjiang <br>
	 * 创建日期:2017年11月21日 <br>
	 * 修改者: mender <br>
	 * 修改日期: modifydate <br>
	 * @param sql
	 * @return
	 */
	public Long queryCountMessage(String sql) {
		
		Long queryCount = jdbcTemplate.queryForObject(sql, Long.class);
		
		return queryCount;
	}
	
	/**
	 * 功能: 公共查询接口<br>
	 * 作者: yangjingjiang <br>
	 * 创建日期:2017年11月17日 <br>
	 * 修改者: mender <br>
	 * 修改日期: modifydate <br>
	 * @param params
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object queryCommon(Map<String,String> params) {
		
		Class entityClass = MessageCommon.class;
		
		String tableName = NameUtil.getTableName(entityClass.getSimpleName());
		
		String selectSql = SqlTools.getSelectAllProperty(tableName, entityClass);
		
		List queryForList = jdbcTemplate.query(selectSql, new BeanPropertyRowMapper(entityClass));
		
		Data dt = new Data<>();
		String sqlCount = SqlTools.getCountSql(tableName);
		dt.setTotal((Long)queryCountMessage(sqlCount));
		dt.setRows(queryForList);
		
		
		MessageResult rs = new MessageResult("true", "200", "加载数据成功！", dt);
		
		
		return rs;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object queryStatMessageByCenter(Map<String,String> params) {

		
		StringBuilder sb = new StringBuilder();
		
		String unionAll = " UNION ALL ";
		
		//获取注册过的消息类型
		for (Class classTemp : MessageRegisterCenter.messageType) {
			
			String type = classTemp.getSimpleName().substring(MessageConstants.MESSAGE.length());
			
			String tableName = NameUtil.getTableName(type);
			
			sb.append("SELECT  category, count(").append(type.toLowerCase()).append("_id) as total, sum(case when send_state = '00' then 1 else 0 end) as wait_num,sum(case when send_state = '100' then 1 else 0 end) as success_num,sum(case when send_state = '201' then 1 else 0 end) as retry_num,sum(case when send_state = '200' then 1 else 0 end) as fail_num, sum(case when send_state = '300' then 1 else 0 end) as canl_num   FROM ").append(tableName).append(" WHERE 1=1 GROUP BY category");
			
			sb.append(unionAll);
			
		}
		
		String selectSql = sb.toString().substring(0, sb.length()-unionAll.length());

		List<GeneralMessage> queryList = jdbcTemplate.query(selectSql, new BeanPropertyRowMapper(GeneralMessage.class) );
		
		Data<GeneralMessage> dt = new Data<>();
		String sqlCount = "select count(*) from ("+selectSql+") sum_table";
		dt.setTotal((Long)queryCountMessage(sqlCount));
		dt.setRows(queryList);
		
		MessageResult rs = new MessageResult("true", "200", "加载数据成功！", dt);
		
		return rs;
	}
	
	public static void main(String[] args) {
		
		System.out.println(MessageSms.class.getSimpleName().substring(MessageConstants.MESSAGE.length()));
		
	}
}
